package com.baizhi.controller;

import com.baizhi.entity.CmfzAdmin;
import com.baizhi.service.AdminService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("admin")
public class AdminController {
    @Autowired
    private AdminService as;

    @RequestMapping("selectOne")
    public String selectOne(CmfzAdmin cmfzAdmin, HttpSession session, String code){
       String code1 = (String) session.getAttribute("code");
        System.out.println(code1);
       if(code1!=null&&code1.equals(code)){
           CmfzAdmin cmfzAdmin1 = as.selectOne(cmfzAdmin.getId());
           if(cmfzAdmin1 !=null){
               if(cmfzAdmin.getPassword().equals(cmfzAdmin1.getPassword())){
                   session.setAttribute("admin", cmfzAdmin1);
                   return "redirect:/main.jsp";
               }else{
                   return "密码错误！";
               }
           }else {
               return "账户未注册！";
           }
       }else {
           return "验证码错误!";
       }


    }
    @ResponseBody
    @RequestMapping("allAdmin")
    public Map allAdmin(@RequestParam(defaultValue = "1",value = "page") int pageNo,@RequestParam(defaultValue = "3",value = "limit")
            int pageSize){
        Page<CmfzAdmin> cmfzAdminPage = as.adminListByPage(pageNo, pageSize);

        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        map.put("msg","");
        map.put("count",cmfzAdminPage.getTotal());
        map.put("data",cmfzAdminPage.getRecords());
        return map;

    }

    @RequestMapping("addAdmin")
    @ResponseBody
    public Boolean addAdmin(CmfzAdmin admin){
        try {
            as.insert(admin);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return  false;
        }
    }
    @ResponseBody
    @RequestMapping("delAdmin")
    public Boolean delAdmin(int id){
        try {
            as.delete(id);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @ResponseBody
    @RequestMapping("updAdmin")
    public Boolean updAdmin(CmfzAdmin admin){
        System.out.println(admin);
        try {
            as.update(admin);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return  false;
        }
    }




}
